import {Injectable} from '@nestjs/common';
import {InjectRepository} from '@nestjs/typeorm';
import {Repository} from 'typeorm';
import {OptionEntity} from '../entities/Option.entity';
import {QuestionEntity} from '../entities/Question.entity';
import {SurveyEntity} from '../entities/Survey.entity';
import {SurveyQuestionEntity} from '../entities/SurveyQuestion.entity';
import {ResponseEntity} from '@src/modules/Survey/entities/Response.entity';

@Injectable()
export class SurveyService {

  constructor(
    @InjectRepository(SurveyEntity)
    private readonly surveyRepository: Repository<SurveyEntity>,
    @InjectRepository(ResponseEntity)
    private readonly responseRepository: Repository<ResponseEntity>,
  ) {
  }

  async findSurveyWithQuestionsAndOptions(surveyId: string) {
    if (!surveyId) {
      throw new Error('请填写正确的surveyId');
    }

    const survey = await this.surveyRepository.findOne({
      where: {id: surveyId},
      relations: [
        'questions', // 从Survey到SurveyQuestion的关联
        'questions.question', // 从SurveyQuestion到Question的关联
        'questions.question.options', // 从Question到Option的关联
      ],
    });


    // 手动排序
    if (survey && survey.questions) {
      // 根据surveyOrder字段排序
      survey.questions.sort((a, b) => a.surveyOrder - b.surveyOrder);

      // 对每个问题的选项按照选项ID进行排序
      survey.questions.forEach(question => {
        question.question.options.sort((a, b) => parseInt(a.id) - parseInt(b.id));
      });
    }

    return survey;
  }

  async saveSurvey(responses: ResponseEntity[], SurveyId: string, RespondentId: string) {

    if (!SurveyId || !RespondentId) {
      throw new Error('surveyId或respondentId不存在');
    }

    console.log(SurveyId, RespondentId);


    // 检查数据库中是否已经存在相同问卷ID和相同填写者ID的记录
    const existingResponse = await this.responseRepository.findOne({
      where: {SurveyId, RespondentId},
    });

    console.log("existingResponse", existingResponse);

    // 如果已经存在相同问卷ID和相同填写者ID的记录，则返回相应的提示消息
    if (existingResponse) {
      throw new Error('您已经填写过该调查表了，请勿重复提交!');
    }

    // 遍历每个提交的回答
    for (const response of responses) {
      // 创建一个新的实体对象来保存到数据库
      const newResponse = new ResponseEntity();
      newResponse.SurveyId = response.SurveyId;
      newResponse.QuestionId = response.QuestionId;
      newResponse.OptionId = response.OptionId;
      newResponse.RespondentId = response.RespondentId;
      newResponse.ResponseDateTime = response.ResponseDateTime;
      await this.responseRepository.save(newResponse);
    }

    return '提交成功';


  }

}
